import React from 'react';

import { Game, createCatchZongZi, SPEED_LEVEL } from '../../services/game-engine';
import styles from './index.css';

const config = {};

interface GameBoxProps {
  speedLevel: SPEED_LEVEL;
  timeLimit: number;
  children: React.ReactNode;
  wrappedGame?(game: Game): void;
  onUpdateTime(n: number): void;
  onUpdateScore(n: number): void;
  onGameOver: ({ status: END_STATUS, score: number }) => void;
}

class GameBox extends React.Component<GameBoxProps> {
  private boxId = `_${Date.now()}`;

  private game?: Game;

  componentDidMount() {
    const container = this.container();
    if (!container) return;
    const {
      speedLevel,
      timeLimit,
      wrappedGame,
      onUpdateTime,
      onUpdateScore,
      onGameOver,
    } = this.props;

    const formatImage = data => ({
      src: data.src,
      top: data.originStyle.top,
      left: data.originStyle.left,
      width: data.originStyle.width,
      height: data.originStyle.height,
    });
    const data = {
      src: 'https://p-cdn1.rabbitpre.com/0ab78b2e-6882-4c42-b305-f48c25768770?imageMogr2/auto-orient/format/webp',
      top: 0,
      
    }
    this.game = createCatchZongZi({
      el: container,
      resources: {
        fallingItemElement: formatImage(''),
        fallingBlockElement: formatImage(''),
        receiveElement: formatImage(''),
        scoreAddElement: formatImage(''),
      },
      speedLevel,
      timeLimit,
      timeListeners: [onUpdateTime],
      scoreListeners: [onUpdateScore],
      gameOver: onGameOver,
    });
    wrappedGame && wrappedGame(this.game);
    window.addEventListener('resize', this.resize);
  }

  componentWillUnmount() {
    this.game?.destroy();
    window.removeEventListener('resize', this.resize);
  }

  private resize = () => {
    this.game?.resize();
  };

  private container = (): HTMLDivElement =>
    document.getElementById(this.boxId) as HTMLDivElement;

  render() {
    const { children } = this.props;
    return (
      <div
        id={this.boxId}
        className={styles.container}
        style={{
          backgroundImage: `url()`,
        }}>
        {children}
      </div>
    );
  }
}

export default GameBox;
